//
//  RxSwiftObjectMapperViewController.swift
//  SwiftRx研究
//
//  Created by 世霖 on 2020/7/17.
//  Copyright © 2020 世霖. All rights reserved.
//

import UIKit
import RxCocoa
import RxDataSources
import RxSwift
import ObjectMapper

public enum RxObjectMapperError : Error {
    case parsingError
}

//扩展映射方法
public extension Observable where Element : Any {
    func mapObject<T>(type : T.Type) -> Observable<T> where T: Mappable {
          let mapper = Mapper<T>()
        return self.map { (element) -> T in
                  guard let parsedElement = mapper.map(JSONObject: element) else {
                      throw RxObjectMapperError.parsingError
                  }
                  return parsedElement
              }
        
    }
    
    public  func mapArray< T>(type:T.Type) -> Observable<[T]> where T:Mappable  {
        let mapper = Mapper<T>()
        return self.map { (element) -> [T] in
                 guard let parsedArray = mapper.mapArray(JSONObject: element) else {
                     throw RxObjectMapperError.parsingError
                 }
                  
                 return parsedArray
             }
        
    }
    
    
}








public class RxSwiftObjectMapperViewController: UIViewController {

    let disposeBag = DisposeBag()
    
    var  tableView:UITableView!
    
    
    
    public override func viewDidLoad() {
        super.viewDidLoad()
        
        initDataSource()
        
           //创建表格视图
           self.tableView = UITableView(frame: self.view.frame, style:.plain)
           //创建一个重用的单元格
           self.tableView!.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
           self.view.addSubview(self.tableView!)

        
        //创建URL对象
          let urlString = "https://www.douban.com/j/app/radio/channels"
          let url = URL(string:urlString)
          //创建请求对象
          let request = URLRequest(url: url!)
        //获取列表数据
//               let data = URLSession.shared.rx.json(request: request)
//                   .mapObject(type: DouBan.self)
//                   .map{ $0.channels ?? []}
//        
        //获取列表数据
            let data = URLSession.shared.rx.json(request: request)
                .mapObject(type: DouBan.self)
                .map{ $0.channels ?? []}
             
            //将数据绑定到表格
            data.bind(to: tableView.rx.items) { (tableView, row, element) in
                let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
                cell.textLabel?.text = "\(row)：\(element.name!)"
                return cell
            }.disposed(by: disposeBag)
        
        
        
        
        
        
        
//        5:使用文件流的形式上传文件
        let  fileURL = Bundle.main.url(forResource: "hangge", withExtension: "zip")
        let uploadurl = URL(string: "https")
        
//        将文件上传到服务器
    
        
    }
    
    func initDataSource() {
        //创建URL对象
        let urlString = "https://www.douban.com/j/app/radio/channels"
        let url = URL(string:urlString)
        //创建请求对象
        let request = URLRequest(url: url!)
         
        //创建并发起请求
        URLSession.shared.rx.json(request: request)
            .mapObject(type: DouBan.self)
            .subscribe(onNext: { (douban: DouBan) in
                if let channels = douban.channels {
                    print("--- 共\(channels.count)个频道 ---")
                    for channel in channels {
                        if let name = channel.name, let channelId = channel.channelId {
                            print("\(name) （id:\(channelId)）")
                        }
                    }
                }
            }).disposed(by: disposeBag)
        
        
        
        
        
    }

}
